<template>
  <el-form ref="ruleFormRef" :model="formData" label-width="80px" class="demo-ruleForm" :size="formSize">
    <el-row :gutter="24">
      <el-col :span="item.span" v-for="item in formItems" :key="item.prop">
        <el-form-item :label="item.label + ':'" :prop="item.prop">
          <component
            :is="ItemMap[item.name]"
            :item-config="item"
            :item-value="formData[item.prop]"
            :corr-value="item.corrProp ? formData[item.corrProp] : null"
            :ref="item.prop"
            @update="handleUpdate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="toolSpan">
        <div :style="toolSpan === 24 ? 'text-align:right;' : 'text-align:left;'">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </div>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
  import { reactive, ref, watch, toRefs, PropType } from 'vue';
  import { BaseFormItem } from './common-form-type';
  import { ItemMap } from './items';

  interface FD {
    fd: any;
    rules?: any;
  }

  const getFormData = (arr: Array<BaseFormItem>): FD => {
    let fd: any = {};

    arr.forEach((item) => {
      fd[item.prop] = item.defaultValue;
    });

    return { fd };
  };

  const takeToolSpan = (arr: Array<BaseFormItem>): number => {
    let sum = arr.reduce((total, curr) => {
      return total + (curr.span ? curr.span : 0);
    }, 0);

    return sum % 24 === 0 ? 24 : arr[0].span ? arr[0].span : 6;
  };

  const props = defineProps({
    formItems: { type: Array as PropType<Array<BaseFormItem>>, default: () => [] },
  });

  const { formItems } = toRefs(props);
  const formData = reactive(getFormData(formItems.value).fd);
  const formSize = ref('');
  const toolSpan = ref(takeToolSpan(formItems.value));

  watch(formData, (v, o) => {
    console.log('v=', v, ',o=', o);
  });

  const handleUpdate = (c: any): void => {
    formData[c.prop] = c.val;
  };

  const emits = defineEmits({
    handleSearch: null,
  });
  const handleSearch = (): void => {
    emits('handleSearch', formData);
  };
  const handleReset = (): void => {
    formItems.value.forEach((item: any) => {
      formData[item.prop] = item.defaultValue;
    });
    emits('handleSearch', formData);
  };

  defineExpose({ formData });
</script>
